package com.yxzr.youyou.retrofit;

import android.content.Context;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDailog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * Created by 18354 on 2018-04-08.
 */

public abstract class BaseObserver implements Observer<ResponseBody> {
    private Context mContext;
    private LoadingDailog dialog;
    private String result = "";
    private boolean isShow = true;
    public BaseObserver(Context cxt,boolean isShow) {
        this.mContext = cxt;
        LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(cxt)
                .setMessage("加载中...")
                .setCancelable(false)
                .setCancelOutside(false);
        dialog = loadBuilder.create();

        this.isShow = isShow;
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (isShow){
            dialog.show();
        }
    }

    @Override
    public void onNext(ResponseBody value) {

        try {
            result = value.string();
            JSONObject jsonObject = new JSONObject(result);
            int status = jsonObject.getInt("status");
            if (status == 200){
                onSuccees(result);
            }else {
                String msg = jsonObject.getString("msg");
                if (msg.contains("查询") || msg.contains("签到") || msg.contains("请先登")){

                }else {
                    Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                }
                onFail(status);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onError(Throwable e) {
        onErr(e);
        if (isShow){
            dialog.dismiss();
        }

    }

    @Override
    public void onComplete() {
        onComp();
        if (isShow){
            dialog.dismiss();
        }
    }

    /**
     * 返回成功
     *
     * @param t
     * @throws Exception
     */
    protected abstract void onSuccees(String t);


    protected abstract void onFail(int error_code);

    /**
     * 完成
     */
    protected abstract void onComp();

    /**
     * 错误
     */
    protected abstract void onErr(Throwable e);

}
